<template>
  <div>
    <div style="margin:0 auto; width:900px; font-size:14px;">
      <div class="headFixed">
        <el-row :gutter="20">
          <el-col :span="5">
            <div style="padding-left:20px;padding-top:10px">
              <span style="font-weight:bold">填写人：</span>
              <span style="color:#444444">{{userInfoData.realName}}</span>
            </div>
          </el-col>
          
          <el-col :span="5">
            <div style="padding-left:20px;padding-top:10px">
              <span style="font-weight:bold">测试时长：</span>
              <span style="color:#444444">90分钟</span>
            </div>
          </el-col>
          <el-col :span="4">
            <div style="padding-left:20px;padding-top:10px">
              <span style="font-weight:bold">耗时：</span>
              <span style="color:#444444">{{useTime}}</span>
            </div>
          </el-col>
          <el-col :span="3">
            <div style="padding-left:20px;padding-top:3px">
                <el-button size="small" @click="postionUnselect(12)">定位未答题</el-button>
            </div>
          </el-col>
          <el-col :span="7">
            <div style="padding-left:20px;padding-top:10px">
              <el-row>
                <el-col span="5">
                  <span style="font-weight:bold">进度：</span>
                </el-col>
                 <el-col span="18">
                   <el-progress :text-inside="true" :stroke-width="16"  :percentage="progress"></el-progress>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="headImg">
      <img src="img/bg/head.png" />
    </div>
    <div  class="sheetContent">
      <div class="headStyle">
        卡特尔16项人格测试  
      </div>
      <div v-for="(item, index) in data" :key="index" class="itemStyle">
        <div :id="'unSelect'+index" class="titleStyle">
            {{ item.topicNum }}. {{ item.topicContent }}
        </div>
         <div style="padding-left: 20px">
            <el-radio-group
              v-model="item.userAnswer"
              @change="changeUpdate(item)"
              
            >
              <el-radio
                v-for="(subjectItem, indx) in item.optionList"
                :label="subjectItem.key"
                :key="indx"
                :disabled="userInfoData.endFlag == '完成'"
                style="display: block; width: 700px; padding-top:5px"
                @on-keypress="e =>{if(e.keyCode == 32) e.returnValue = false;}"
                >
                {{subjectItem.key + '.'+ subjectItem.value}}
                </el-radio>
            </el-radio-group>
        </div>
      </div>
      <div style="text-align: center">
        <el-button size="small" type="primary" :disabled="userInfoData.endFlag == '完成'" @click="savaQuestionData"> 提交 </el-button>
      </div>
    </div>
    <div style="text-align: center; padding-bottom: 50px; font-size: 14px">
      由独领云科技 <span style="color: #666666"> 提供技术支持</span>
    </div>
  </div>
</template>

<script>
import {exportBizSixteenUserAnalysisExcel,saveOrUpdateBizSixteenUserAnalysis,saveOrUpdateBizSixteenUserAnalysisList,saveBizSixteenUserAnalysis,saveBizSixteenUserAnalysisList,deleteBizSixteenUserAnalysis,queryBizSixteenUserAnalysis,queryBizSixteenUserAnalysisListPage,updateBizSixteenUserAnalysis,deleteBizSixteenUserAnalysisList} from '@/api/biz/sixteen/bizSixteenUserAnalysisApi';
import {exportBizSixteenUserInfoExcel,saveOrUpdateBizSixteenUserInfo,saveOrUpdateBizSixteenUserInfoList,saveBizSixteenUserInfo,saveBizSixteenUserInfoList,deleteBizSixteenUserInfo,queryBizSixteenUserInfo,queryBizSixteenUserInfoListPage,updateBizSixteenUserInfo,deleteBizSixteenUserInfoList} from '@/api/biz/sixteen/bizSixteenUserInfoApi';
import {exportBizSixteenUserAnswersExcel,saveOrUpdateBizSixteenUserAnswers,saveOrUpdateBizSixteenUserAnswersList,saveBizSixteenUserAnswers,saveBizSixteenUserAnswersList,deleteBizSixteenUserAnswers,queryBizSixteenUserAnswers,queryBizSixteenUserAnswersListPage,updateBizSixteenUserAnswers,deleteBizSixteenUserAnswersList} from '@/api/biz/sixteen/bizSixteenUserAnswersApi';
import { mapGetters } from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import { regionData, CodeToText } from 'element-china-area-data';
import { getToken } from '@/util/auth';
import { Base64 } from 'js-base64';
import NProgress from 'nprogress';
export default {
  data() {
    return {
      //进度
      progress: 0,
      //耗时统计
      useTime: '0分0秒',
      seconds: 0,
      //页面是否有效
      isValid: true,

      checkList: [],
      loading: false,
      radio: '',
      data: [],
      userInfoData: {},
      userInfoId: '',
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition: [],
        orderRule: [],
        currentPage: 1,
        pageSize: 10,
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {},
    };
  },
  computed: {
    ...mapGetters([
      'website',
      'orgTree',
      'genOrgTree',
      'userInfo',
      'permission',
      'projectInfo',
    ]),
  },
  methods: {
    /**
     * 加载下发列表信息
     */
    loadUserInfo() {
      this.reqParams = {
        singleBody: {
          id: this.userInfo.userId,
        },
      };
      let commonData = reqCommonMsg(this.reqParams);
      queryBizSixteenUserInfo(commonData).then((res) => {
        this.userInfoData = res.data.body.singleBody;
        this.seconds = this.userInfoData.takeTime;
      },(error) => {
        this.$console.log(error);
      }
      );
    },
   
    /**
     * 加载题目列表数据
     */
    onLoad(page) {
      this.reqParams = {
        singleBody: {
          userName: this.userInfo.userName,
        },
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: {
          prop: 'id',
          order: 'ascending',
        },
        currentPage: 1,
        pageSize: 99999,
      };
      this.commonData = reqCommonMsg(this.reqParams);
      queryBizSixteenUserAnswersListPage(this.commonData).then((res) => {
        this.data = res.data.body.listBody;
        if(this.data.length == 0){
          this.$message({
            type: 'warning',
            message: '题目不存在，请联系管理员!'
          });
        }
        this.data.forEach((element) => {
          element.optionList = [];
          let optionArray = element.options.split(',');
          optionArray.forEach((optionElement) => {
            let keyValue = optionElement.split('.')
            element.optionList.push(
              {
                key: keyValue[0].trim(),
                value: keyValue[1].trim()
              }
            )
          });
        });
        console.log('this.data==',this.data);
        this.loading = false;
        this.computedProgress();
      },
      (error) => {
        this.loading = false;
      }
      );
    },
    /**
     * 修改一条记录
     */
    changeUpdate(item) {
      this.$console.log('this.data:',this.data);
      //计算进度
      this.computedProgress();
      //计算用户得分
      if(item.userAnswer == item.rightAnswer){
        item.userAnswerScore = item.rightAnswerScore;
      }
      else if(item.userAnswer == item.preAnswer){
        item.userAnswerScore = item.preAnswerScore;
      }
      else{
        item.userAnswerScore = 0;
      }
      item.dateTime = this.$toolUtil.formatTimes(new Date())
      this.reqParams.singleBody = item;
      this.commonData = reqCommonMsg(this.reqParams);
      updateBizSixteenUserAnswers(this.commonData).then((res) => {
        item = res.data.body.singleBody;
        this.data.forEach((element) => {
          if (element.id == item.id) {
            element.dataSign = item.dataSign;
          }
        });
        this.singleBody = {};
      },(error) => {
        this.$console.log(error);
      });

      //更新进度
      if(this.userInfoData.answerBeginTime == ''){
        this.userInfoData.answerBeginTime = this.$toolUtil.formatTimes(new Date())
      }
      this.userInfoData.progressRate = this.progress;
      this.userInfoData.takeTime = this.seconds;
      this.userInfoData.endFlag = '进行中';
      this.reqParams.singleBody = this.userInfoData;
      // 解析用户名（用户ID）
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizSixteenUserInfo(this.commonData).then((res) => {
        this.userInfoData = res.data.body.singleBody;
        this.$console.log('更新用户信息成功。。。');
      }, error => {
        this.$console.log(error);
      });
    },
    /**
     * 计算完成进度
     */
    computedProgress(){
      let doCnt=0;
      let allCnt=0;
      this.data.forEach((element) => {
        allCnt++;
        if(element.userAnswer != '') {
          doCnt++;
        }
      });
      this.progress = parseFloat(doCnt * 100 / allCnt).toFixed(2);
    },
    /**
     * 定位到未选题
     */
    postionUnselect(index){
      for (var i = 0; i < this.data.length; i++)
      { 
        if(this.data[i].userAnswer == ''){
          location.href = '#unSelect' + this.data[i-2].topicNum;
          i = 1000;
        }
      }
    },
    /**
     * 保存问卷信息
     */
    savaQuestionData() {
      let finished = true;
      for (var i = 0; i < this.data.length; i++){ 
        if(this.data[i].dateTime == ''){
          this.$message({
            type: 'warning',
            message: '第'+this.data[i].topicNum+'题未选择，请重新勾选!'
          });
          finished = false;
          location.href = '#unSelect' + this.data[i-2].topicNum;
          i = 1000;
        }
      }
      if(!finished){
        return false;
      }
      
      this.$confirm('确定要提交测试卷?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //更新进度
          this.userInfoData.answerEndTime = this.$toolUtil.formatTimes(new Date())
          this.userInfoData.progressRate = this.progress;
          this.userInfoData.takeTime = this.seconds;
          this.userInfoData.endFlag = '完成';
          this.reqParams.singleBody = this.userInfoData;
          // 解析用户名（用户ID）
          this.commonData = reqCommonMsg(this.reqParams)
          updateBizSixteenUserInfo(this.commonData).then((res) => {
            this.userInfoData = res.data.body.singleBody;
            this.$console.log('提交成功。。。');
          }, error => {
            this.$console.log(error);
          });

          //提交并处理结果
          this.reqParams.singleBody = {};
          this.commonData = reqCommonMsg(this.reqParams)
          saveBizSixteenUserAnalysis(this.commonData).then(() => {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.$console.log('this.userInfoData==',this.userInfoData);
            this.$router.push({path: '/sixteen/submitSuccess',query:{'tenantId': Base64.encode(this.userInfo.tenantId),'userId':Base64.encode(this.userInfo.userId)}});
          }, error => {
            this.$console.log(error);
          });         
        }).catch(() => {});
    },
  },
  created() {
    
  },
  mounted() {
    window.onbeforeunload = e => {      //刷新时弹出提示
      return ''
    };
    //加载问卷题单信息
    this.loadUserInfo();
    //加载数据
    this.onLoad(this.page);

    //统计耗时
    setInterval(() => {
      this.seconds++;
      var minutes = Math.floor(this.seconds / 60);
      var sec = this.seconds % 60;
      this.useTime= minutes + '分' + sec + '秒';
    }, 1000);
  },
};
</script>
<style  lang="scss">
html,
body,
#app {
  height: 100%;
  overflow: auto;
  margin: 0;
  padding: 0;
  background: #edf2f7 !important;
}
.headFixed {
  margin: 0 auto;
  width: 900px;
  position: fixed;
  background: #e0e0e0;
  z-index: 1000;
  border-bottom: 1px solid #7a7b7e;
  height: 40px;
}
.headImg {
  margin: 0 auto;
  width: 900px;
  padding-top: 40px;
}

.sheetContent {
  margin: 0 auto;
  width: 900px;
  margin-bottom: 50px;
  padding: 30px;
  background-color: #ffffff;
}

.headStyle {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
}
.noticeStyle {
  font-size: 14px;
  padding-top: 20px;
  line-height: 1.8;
}
.titleStyle {
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 5px;
  padding: 5px 0px 5px 5px;
  // background-color: #eeeeee;
  background-image: linear-gradient(#eeeeee, #fff);
}
.itemStyle {
  margin-bottom: 10px;
}
</style>
